﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WorkBasket.Data.Repository;
using WorkBasket.Infrastructure;
using WorkBasket.Models;
using WorkBasket.Data.Entities;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace WorkBasket.Controllers
{
    public class FormController : Controller
    {
        // GET: Form
 
           
        private SOC soc = new SOC(new MyContext());
 
 
 
        public ActionResult Edit(int WorkflowID=0,int InstanceID=0,int StepID=0)
        {
            FormModel FormModel = new FormModel();
            Step step = null;


            if (StepID == 0) {
                FormModel.WorkflowID = WorkflowID;
                step = soc.Execute<Step>("GetWorkflowTrigger @WorkflowID", new SqlParameter("WorkflowID", WorkflowID)).FirstOrDefault();
             
            }
            else
            {
                step = soc.Steps.GetByID(StepID);
                ProcessVersion pv = soc.ProcessVersions.GetByID(step.ProcessVersionID);


                FormModel.WorkflowID =(int)pv.WorkflowID;
            }



                FormModel.Form = soc.Forms.GetByID(step.WorkbasketFormID);
                FormModel.StepID = step.StepID;
                
                FormModel.InstanceID = InstanceID;
                FormModel.InstanceData = GetInstanceData(InstanceID);
                FormModel.ProcessVersionID = step.ProcessVersionID;

            return View(FormModel);
        }
 


        private Dictionary<string, string> GetInstanceData(int InstanceID)
        {

 //get last updated version of the InstanceData from the history
          InstanceHistory ih = soc.InstanceHistorys.Where(c => c.InstanceID == InstanceID)
                .OrderByDescending(t => t.TimeStamp).FirstOrDefault();
             string json = string.Empty;
             JavaScriptSerializer serializer = new JavaScriptSerializer();
          if (ih != null) {  
             
              json = ih.InstanceData;

             }
            return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);  
      
        }
        
    }
}